package cn.maven.main;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

public class Generator {
    private Configuration configuration;

    //1、完成环境的初始化
    public void init(String path) throws IOException {
        //Configuration实例化
        configuration = new Configuration(Configuration.getVersion());
        //设置模板所在路径
        configuration.setDirectoryForTemplateLoading(new File(path));
    }

    //2、生成模板
    public void process(String tempName, String savePath, Map<String, Object> map) throws IOException, TemplateException {
        //获取模板对应实例
        Template template = configuration.getTemplate(tempName);
        //初始化保存路径
        FileOutputStream fileOutputStream = new FileOutputStream(savePath);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        //传参   生成数据
        template.process(map, outputStreamWriter);
    }


    //1、完成环境初始化
  /* public void init() throws IOException {
        //Configuration实例化
       configuration = new Configuration(Configuration.getVersion());
       //获取模板所在路径
       String path=this.getClass().getClassLoader().getResource("").getPath();
       configuration.setDirectoryForTemplateLoading(new File(path));
   }*/

  /**
     * @param savePath (文件路径)
     * @param tempName （模板文件名称）
     * @throws IOException
     */
   /*public void process(String tempName,String savePath) throws IOException, TemplateException {
       //获取模板对应实例
       Template template=configuration.getTemplate(tempName);
       //组装数据
       Map param=new HashMap();
       param.put("name","张三");
       //初始化保存路径
       FileOutputStream stream=new FileOutputStream(savePath);
       OutputStreamWriter writer=new OutputStreamWriter(stream);
       //传参生成模板
       template.process(param,writer);

   }

    public static void main(String[] args) {
        Generator generator=new Generator();

        try {
            generator.init();
            generator.process("hello.ftl","存放路径+文件名.后缀");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }*/











}
